package com.demo.async;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageClientExt;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class AsyncConsumer {

    public static void main(String[] args) throws InterruptedException, MQClientException {

        // Instantiate with specified consumer group name.
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("async_topic_test1");

        // Specify name server addresses.
        consumer.setNamesrvAddr("localhost:9876");

        // Subscribe one more more topics to consume.
        consumer.subscribe("Jodie_topic_1023", "*");
        // Register callback to execute on arrival of messages fetched from brokers.
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                for (int i = 0; i < msgs.size(); i++) {
//                    System.out.println("thread "+Thread.currentThread().getId() + " receive message: "+
//                            new String( msgs.get(i).getBody()) +
//                            "   message id : "+msgs.get(i).getMsgId()+
//                            "  message key:"+msgs.get(i).getKeys());
                    MessageClientExt messageClientExt = (MessageClientExt) msgs.get(i);
                    System.out.println("thread "+Thread.currentThread().getId() + " receive message: "+
                            new String(messageClientExt.getBody()) +
                            "   message id : "+messageClientExt.getMsgId()+
                            "   offset id :" + messageClientExt.getOffsetMsgId()+
                            "   message key:"+messageClientExt.getKeys());
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        //Launch the consumer instance.
        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}